const $ = ele => document.querySelector(ele) ;

const ajax = function(options){
    const {
        method="get",
        url,
        contentType=true,
        async=true,
        dataType='text',
        data={},
        success
    } = options ; 

    let params = contentType?getSearch(data):data ; 
    let xhr ;
    if( window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject();
    }
    if( method.toLowerCase() == 'get' ){
        url = url + "?" + params ;
    }
    xhr.open( method , url , async ) ;
    if( method.toLowerCase() == 'get' ){
        xhr.send();
    } else if ( method.toLowerCase() == 'post' ) {
        if( contentType ){
            xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
            xhr.send( params ) ;
        } else {
            xhr.send( params );
        }
    }
    xhr.onreadystatechange = function () {  
        if( xhr.readyState === 4 && xhr.status === 200 ) {
            let res = xhr.responseText ;
            if( dataType.toLowerCase() === 'json' ) {
                res = JSON.parse( res )
            }
            success(res) ;
        }
    }
}
function getSearch(obj){
    str = '' ;
    for( let key in obj ){
        str = str+key+"="+obj[key]+"&";
    }
    str = str.substr(0,str.length-1);
    return str ; 
}